package com.ithuameng.cosy.coder.json;

import com.ithuameng.cosy.model.Ping;
import com.ithuameng.cosy.model.Transportable;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.json.JsonMapper;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.util.List;

/**
 * websocket协议 json消息体编码
 *
 * @author ithuameng
 */
public class TextMessageEncoder extends MessageToMessageEncoder<Transportable> {

    private static final JsonMapper OBJECT_MAPPER = JsonMapper.builder()
            .serializationInclusion(JsonInclude.Include.NON_NULL)
            .build();

    @Override
    protected void encode(ChannelHandlerContext ctx, Transportable data, List<Object> out) throws JsonProcessingException {

        TransmitBody protocol = new TransmitBody();
        protocol.setType(data.getType().getValue());
        protocol.setContent(getBody(data));

        TextWebSocketFrame frame = new TextWebSocketFrame(OBJECT_MAPPER.writeValueAsString(protocol));

        out.add(frame);
    }

    private String getBody(Transportable data) throws JsonProcessingException {
        if (data instanceof Ping) {
            return null;
        }
        return OBJECT_MAPPER.writeValueAsString(data);
    }
}
